<?php
// +----------------------------------------------------------------------
// | HkCms 网站前台主题管理
// +----------------------------------------------------------------------
// | Copyright (c) 2012-2019 http://www.hkcms.cn, All rights reserved.
// +----------------------------------------------------------------------
// | Author: 广州恒企教育科技有限公司 <admin@hkcms.cn>
// +----------------------------------------------------------------------

namespace app\template\controller;

use common\controller\AdminBase;
use think\Db;
use think\Validate;

class Theme extends AdminBase {

    //主题显示
    public function index()
    {
        $filed = glob(TEMPLATE_PATH . '*');
        $count = 0;
        $arr = [];
        foreach ($filed as $key => $v) {
            if (is_dir($v) == false) {
                continue;
            }
            $arr[$key]['name'] = basename($v);
            if (is_file(TEMPLATE_PATH . $arr[$key]['name'] . '/preview.jpg')) {
                $arr[$key]['preview'] = self::$Cache["Config"]['siteurl'] . str_replace(SITE_PATH, "", TEMPLATE_PATH) . $arr[$key]['name'] . '/preview.jpg';
            } else {
                $arr[$key]['preview'] = self::$Cache["Config"]['siteurl'] . 'statics/images/nopic.jpg';
            }

            $arr[$key]['use'] = 0;
            if (self::$Cache["Config"]['theme'] == $arr[$key]['name']) {
                $arr[$key]['use'] = 1;
            }
            $count ++;
        }

        $this->assign('themes', $arr);
        $this->assign('count', $count);
        return $this->fetch();
    }

    /**
     * 风格选择
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function chose()
    {
        $theme = input('theme');
        if (empty($theme)) {
            $this->error("主题名称不能为空！");
        }
        if ($theme == self::$Cache['Config']['theme']) {
            $this->error("主题未改变！", url("Theme/index"));
        }
        $status = Db::name('config')->where(array('varname' => 'theme'))->update(array('value' => $theme));
        cache('Config',null);
        if ($status !== false) {

            $files1 = glob(TEMPLATE_PATH.$theme.'/content/*.json');
            $files2 = glob(TEMPLATE_PATH.$theme.'/content/*/*.json');
            $data = [];
            if (!empty($files1)) {
                foreach ($files1 as $file) {
                    $data[] = $file;
                }
            }
            if (!empty($files2)) {
                foreach ($files2 as $file) {
                    $data[] = $file;
                }
            }
            if (!empty($data)) {
                foreach ($data as $key=>$value) {
                    $temp = [];
                    $arr = json_decode(file_get_contents($value), true);
                    if (!empty($arr)) {
                        $temp['title'] = $arr['title'];
                        $temp['name'] = $arr['name'];
                        $temp['theme'] = $theme;
                        $temp['file'] = $value;
                        $temp['config'] = json_encode($arr['data']);
                        $temp['create_at'] = time();
                        $add[] = $temp;
                        $id = Db::name('theme_config')->where(['name'=>$arr['name'],'theme'=>$temp['theme']])->value('id');
                        if ($id) {
                            Db::name('theme_config')->where(['id'=>$id])->update($temp);
                        } else {
                            $temp['config_user'] = '';
                            Db::name('theme_config')->insert($temp);
                        }
                    }
                }
            }
            $this->success("更新成功！");
        } else {
            $this->error("更新失败！");
        }
    }

    /**
     * 模板配置操作
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function updateConfig()
    {
        $theme = input('theme');
        if (empty($theme)) {
            $this->error("主题名称不能为空！");
        }
        $files1 = glob(TEMPLATE_PATH.$theme.'/content/*.json');
        $files2 = glob(TEMPLATE_PATH.$theme.'/content/*/*.json');
        $data = [];
        if (!empty($files1)) {
            foreach ($files1 as $file) {
                $data[] = $file;
            }
        }
        if (!empty($files2)) {
            foreach ($files2 as $file) {
                $data[] = $file;
            }
        }
        if (!empty($data)) {
            $not_delete = [];
            foreach ($data as $key=>$value) {
                $not_delete[] = $value;
                $temp = [];
                $arr = json_decode(file_get_contents($value), true);
                if (!empty($arr)) {
                    $temp['title'] = $arr['title'];
                    $temp['name'] = $arr['name'];
                    $temp['theme'] = $theme;
                    $temp['file'] = $value;
                    $temp['config'] = json_encode($arr['data']);
                    $temp['create_at'] = time();
                    $temp['config_user'] = '';
                    $add[] = $temp;
                    $id = Db::name('theme_config')->where(['name'=>$arr['name'],'theme'=>$temp['theme']])->value('id');
                    if ($id) {
                        Db::name('theme_config')->where(['id'=>$id])->update($temp);
                    } else {
                        $temp['config_user'] = '';
                        Db::name('theme_config')->insert($temp);
                    }
                }
            }
            Db::name('theme_config')->where(['theme'=>$theme])->whereNotIn('file',implode(',',$not_delete))->delete();
        } else {
            Db::name('theme_config')->where(['theme'=>$theme])->delete();
        }
        $this->success("更新成功！");
    }

    /**
     * 获取文件列表
     * @return mixed
     */
    public function getFiles()
    {
        $theme = input('theme');
        if (empty($theme)) {
            $this->error("主题名称不能为空！");
        }
        if (!Validate::is($theme,'alphaDash')) {
            $this->error("非法字符！");
        }

        $data = Db::name('theme_config')->where(['theme'=>$theme])->select();
        $this->assign('data',$data);
        $this->assign('theme',$theme);
        return $this->fetch();
    }

    /**
     * 模板设置
     * @return mixed
     */
    public function setting()
    {
        if ($this->request->isPost()) {
            $input = $this->request->only(['config','id']);
            if (empty($input['config']) || !is_array($input['config'])) {
                $this->error("未有配置提交！");
            }
            if (empty($input['id']) || !is_numeric($input['id'])) {
                $this->error("ID格式不正确！");
            }
            $one = Db::name('theme_config')->where(['id'=>$input['id']])->find();
            if (empty($one)) {
                $this->error("未找到对应的配置文件！");
            }
            $array = json_decode($one['config'],true);
            foreach ($input['config'] as $key=>$value) {
                if (isset($value['value']) && isset($array[$key]['value'])) {
                    $array[$key]['value'] = is_array($value['value'])?implode(',',$value['value']):$value['value'];
                    continue;
                } else if (isset($array[$key]['title'])) {
                    $array[$key]['title'] = $value['title'];
                }
                foreach ($value as $k=>$v) {
                    if (isset($v['value']) && isset($array[$key]['data'][$k]['value'])) {
                        $array[$key]['data'][$k]['value'] = is_array($v['value'])?implode(',',$v['value']):$v['value'];
                    }
                }
            }
            $bl = Db::name('theme_config')->where(['id'=>$input['id']])->update(['config_user'=>json_encode($array)]);
            $this->success('保存成功');
        }

        $id = input('id');

        if (empty($id) || !is_numeric($id)) {
            $this->error("ID格式不正确！");
        }

        $one = Db::name('theme_config')->where(['id'=>$id])->find();
        $one['config'] = json_decode($one['config'],true);
        $this->assign('id',$id);
        if (!empty($one['config_user'])) {
            $config_user = json_decode($one['config_user'],true);
            foreach ($config_user as $key=>$value) {
                 if (!empty($value['data'])) {
                     if (isset($value['title'])) {
                         $one['config'][$key]['title'] = $value['title'];
                     }
                     foreach ($value['data'] as $k=>$v) {
                         if (isset($v['value'])) {
                            $one['config'][$key]['data'][$k]['value'] = $v['value'];
                         }
                     }
                } else if (isset($value['value'])) {
                    $one['config'][$key]['value'] = $value['value'];
                }
            }
        }
        $this->assign('data',$one['config']);
        return $this->fetch();
    }
}
